#include <iostream>
#include <string>
#include <sys/eventfd.h>
#include <unistd.h>
#include <pthread.h>
using namespace std;

//唤醒机制是基于文件描述符的
int evfd = -1;

void *wait(void *args)
{
    std::string name = (const char*)args;
    while(true)
    {
        uint64_t flag = 0;//必须是8字节的数据
        ssize_t n = ::read(evfd, &flag, sizeof flag);
        std::cout << name << " 被唤醒, flag: " << flag << ",errno:" << errno << std::endl;
    }
}
void *wakeup(void *args)
{
    std::string name = (const char*)args;
    while(true)
    {
        errno++;//修改errno, 发现errno是每个线程独有一份
        sleep(1);
        std::cout << "wake up one thread, errno: " << errno << std::endl;
        uint64_t flag = 1;
        ::write(evfd, &flag, sizeof flag);
    }
}

int main()
{

    evfd = ::eventfd(0, 0);
    pthread_t td1, td2;

    pthread_create(&td1, nullptr, wait, (void*)"Thread-1");
    pthread_create(&td2, nullptr, wakeup, (void*)"Thread-2");

    pthread_join(td1, nullptr);
    pthread_join(td2, nullptr);

    ::close(evfd);
    return 0;
}